package jn.chen.utils;

import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @className: ToDocx
 * @author: chenLin
 * @version: 1.0.0
 * @description:
 * @date: 24/11/7 007 18:35
 */
@RequestMapping("/toDocx")
@RestController
public class ToDocx {

    @RequestMapping("/docToDocx")
    public void docToDocx(String fileName, HttpServletResponse response) throws IOException {
        response.setHeader("Content-Disposition", "attachment; filename=\"converted.docx\"");
        ServletOutputStream outputStream = response.getOutputStream();
        File inputWord = new File("G:\\download\\converted.doc");

        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
         InputStream docxInputStream = new FileInputStream(inputWord)) {
            boolean flag = true;
            if (flag) {
                // 保存转换后的文件到临时目录
                String tempFilePath = "G:\\" + "converted.docx";
                try (FileOutputStream tempFileOutputStream = new FileOutputStream(tempFilePath)) {
                    byteArrayOutputStream.writeTo(tempFileOutputStream);
                }
                try (InputStream tempFileInputStream = new FileInputStream(tempFilePath)) {
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = tempFileInputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                    }
                }
//                // 删除临时文件
//                File tempFile = new File(tempFilePath);
//                tempFile.delete();
            }
            byteArrayOutputStream.writeTo(outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
